package com.picshare.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;
import java.io.File;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${app.upload.dir:./}")
    private String uploadDir;

    @Value("${app.data.dir:./data}")
    private String dataDir;

    @Value("${app.albums.dir:./albums}")
    private String albumsDir;

    @Value("${app.thumbnails.dir:./thumbnails}")
    private String thumbnailsDir;

    @Value("${app.temp.dir:./temp}")
    private String tempDir;

    @PostConstruct
    public void init() {
        createDirectoryIfNotExists(dataDir);
        createDirectoryIfNotExists(albumsDir);
        createDirectoryIfNotExists(thumbnailsDir);
        createDirectoryIfNotExists(tempDir);
    }

    private void createDirectoryIfNotExists(String path) {
        File directory = new File(path);
        if (!directory.exists()) {
            directory.mkdirs();
        }
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/albums/**")
                .addResourceLocations("file:" + albumsDir + "/");

        registry.addResourceHandler("/thumbnails/**")
                .addResourceLocations("file:" + thumbnailsDir + "/");

        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 安全的跨域配置，允许凭据并指定源
        registry.addMapping("/**")
                .allowedOrigins(
                    "http://localhost:3000",
                    "http://localhost:8080",
                    "http://127.0.0.1:3000",
                    "http://127.0.0.1:8080",
                    "http://localhost:5500",
                    "http://127.0.0.1:5500"
                )
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}